package com.dhwl.hsh.lib.api;

import com.dhwl.hsh.lib.constant.GlobalConfig;
import com.dhwl.hsh.lib.constant.ServerConstant;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * 简要描述
 *
 * @author Derek.Kidd
 * @version V1.0.0
 * @date 2016-04-13 11:12
 */
public class ApiManager {

    private Retrofit retrofit;


    static class ApiHolder {
        private static ApiManager apiManager = new ApiManager();
    }

    /**
     * 获取PhoneApi实例
     *
     * @return
     */
    public static ApiManager getInstance() {
        return ApiHolder.apiManager;
    }


    private ApiManager() {

        retrofit = new Retrofit.Builder()
                .baseUrl(ServerConstant.BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(genericClient())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create()))
                .build();


    }

    public static OkHttpClient genericClient() {

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        Interceptor headerInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request().newBuilder().addHeader("tokenId", GlobalConfig.getInstance().getTokenId()).build();
                return chain.proceed(newRequest);
            }
        };

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(logging)
                .addInterceptor(headerInterceptor)
                .build();
        return httpClient;
    }

    /**
     * 获取UserApi实例
     *
     * @return
     */
    public UserApi getUserApi() {
        return retrofit.create(UserApi.class);
    }

    /**
     * 获取OrderApi实例
     *
     * @return
     */
    public OrderApi getOrderApi() {
        return retrofit.create(OrderApi.class);
    }

    /**
     * 获取OrderApi实例
     *
     * @return
     */
    public TaskApi getTaskApi() {
        return retrofit.create(TaskApi.class);
    }

    /**
     * 获取CommonApi实例
     *
     * @return
     */
    public CommonApi getCommonApi() {
        return retrofit.create(CommonApi.class);
    }
}
